package dgut.party.business.api.pub;

import dgut.party.business.common.enumeration.Priority;
import dgut.party.business.common.util.JsonResult;
import dgut.party.business.common.util.JsonUtils;
import dgut.party.business.common.util.PageableBuilder;
import dgut.party.business.dto.to.ActivityPubTO;
import dgut.party.business.dto.to.InformationPubTO;
import dgut.party.business.dto.to.PublicationDto;
import dgut.party.business.entity.publication.Publication;
import dgut.party.business.service.publication.PublicationRetrieveService;
import dgut.party.business.service.publication.PublicationService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@Log4j2
public class PubController {

  @Autowired
  PublicationService pubService;

  @Autowired
  PublicationRetrieveService pubRetrieveService;

  @RequestMapping("/pub/page")
  public Page<? extends Publication> allAvaliablePubs(@RequestBody Map<String, Object> paramMap) {
    PageableBuilder pageableBuilder = JsonUtils.getObjectFromMap(paramMap.get("pageBuilder"), PageableBuilder.class);
    String keyword = JsonUtils.getObjectFromMap(paramMap.get("keyword"), String.class);
    String pubType = JsonUtils.getObjectFromMap(paramMap.get("pubType"), String.class);
    return this.pubRetrieveService.allAvailablePubsPage(keyword, pubType, pageableBuilder);
  }

  @RequestMapping("/pub/topPubs")
  public List<Publication> topNormalPubs() {
    return this.pubRetrieveService.findLatestTop5Pub(null, Priority.NORMAL);
  }

  @RequestMapping("/pub/detail")
  public Publication pubDetail(@RequestBody Map<String, Object> paramMap) {
    Long pubId = JsonUtils.getObjectFromMap(paramMap.get("pubId"), Long.class);
    return pubRetrieveService.findOneById(pubId);
  }

  @RequestMapping("/pub/create")
  public Map<String, Object> createPublication(@RequestBody Map<String, Object> requestParams) {
    PublicationDto dto = JsonUtils.getObjectFromMap(requestParams, PublicationDto.class);
    Publication result = new Publication();
    if ("info".equals(dto.getType())) {
      InformationPubTO infoTO = new InformationPubTO();
      BeanUtils.copyProperties(dto, infoTO);
      infoTO.setContent((String) requestParams.get("content"));
      result = pubService.createInformationPub(infoTO);
    } else if ("act".equals(dto.getType())) {
      ActivityPubTO actTO = new ActivityPubTO();
      actTO.setContent((String) requestParams.get("content"));
      BeanUtils.copyProperties(dto, actTO);
      result = pubService.createActivityPub(actTO);
    }

    return JsonResult.successJsonResultMap(result);
  }


}
